package com.xyd.Servlet;

import com.xyd.Service.ChildService;
import com.xyd.Service.ParentService;
import com.xyd.Service.ProductService;
import com.xyd.bean.ChildCategory;
import com.xyd.bean.ParentCategory;
import com.xyd.bean.Product;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@WebServlet("/IndexServlet")
public class IndexServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ParentService parentService = new ParentService();
        ChildService childService = new ChildService();
        List<ParentCategory> list = parentService.getAllParent();

        HashMap<ParentCategory, List<ChildCategory>> map = new HashMap<>();

        for (ParentCategory parentCategory :
                list) {
            List<ChildCategory> childCategory = childService.getChildByPId(parentCategory.getParentid());
            map.put(parentCategory, childCategory);
        }

        ProductService productService = new ProductService();
        List<Product> products = productService.getAll();

        List<ChildCategory> childCategoryList = childService.getAllChild();

        HttpSession session = request.getSession();

        session.setAttribute("map", map);
        session.setAttribute("products", products);
        session.setAttribute("childCategoryList",childCategoryList);

        request.getRequestDispatcher("/index.jsp").forward(request, response);

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
